package com.mars.push.core.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.mars.push.core.constant.Constant;
import com.mars.push.core.httpclient.HttpClientService;
import com.mars.push.core.request.PushRequest;
import com.mars.push.core.service.PushService;
import com.mars.push.core.utils.MD5Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author wq
 * @version 1.0
 * @date 2021/03/04 18:40
 */
@Service
@Slf4j
public class VivoPushServiceImpl implements PushService {

    @Resource
    private HttpClientService httpClientService;

    @Value("${push.vivo.appSecret}")
    private String appSecret;

    @Value("${push.vivo.appId}")
    private String appId;

    @Value("${push.vivo.appKey}")
    private String appKey;


    @Override
    public boolean singlePush(PushRequest req) throws Exception {
        String accessToken = getAccessToken();
        JSONObject json = new JSONObject();
        json.put("regId", req.getRegisterId());
        json.put("notifyType", 4);
        json.put("title", req.getTitle());
        json.put("content", req.getContent());
        json.put("timeToLive", 86400);
        //消息类型 0：运营类消息，1：系统类消息。不填默认为0
        json.put("classification", 1);
        //点击跳转类型 1：打开APP首页 2：打开链接 3：自定义 4:打开app内指定页面
        json.put("skipType", 4);
        json.put("skipContent", "intent://com.imlianka.lkapp/guide?" + req.getExtras() + "#Intent;scheme=pushscheme;launchFlags=0x4000000;end");

        json.put("networkType", "1");
        json.put("requestId", accessToken);
        JSONObject jsonObject = httpClientService.doPostJson(Constant.VIVO_SERVER_URL + Constant.VIVO_MESSAGE_SEND, "vivo", accessToken, json);
        log.info("jsonObject===>" + jsonObject);
        return false;
    }

    @Override
    public String getAccessToken() {
        JSONObject json = new JSONObject();
        json.put("appId", appId);
        json.put("appKey", appKey);
        long time = System.currentTimeMillis();
        json.put("timestamp", time);
        String encodeData = appId + appKey + time + appSecret;
        json.put("sign", MD5Utils.stringToMD5(encodeData).toLowerCase());
        JSONObject jsonObject = httpClientService.doPostJson(Constant.VIVO_SERVER_URL + Constant.VIVO_AUTH_URL, "vivo", null, json);
        if (jsonObject.getInteger("result").equals(Constant.ZERO)) {
            return jsonObject.getString("authToken");
        }
        return null;
    }
}
